// Copyright Epic Games, Inc. All Rights Reserved.

#include "logging.h"

#include "config.h"

#include <zencore/filesystem.h>
#include <zencore/fmtutils.h>
#include <zencore/session.h>
#include <zencore/string.h>
#include <zenutil/logging.h>
#include <zenutil/logging/rotatingfilesink.h>

ZEN_THIRD_PARTY_INCLUDES_START
#include <spdlog/spdlog.h>
ZEN_THIRD_PARTY_INCLUDES_END

namespace zen {

void
InitializeServerLogging(const ZenServerOptions& InOptions)
{
	const LoggingOptions LogOptions = {.IsDebug			= InOptions.IsDebug,
									   .IsVerbose		= false,
									   .IsTest			= InOptions.IsTest,
									   .NoConsoleOutput = InOptions.NoConsoleOutput,
									   .AbsLogFile		= InOptions.AbsLogFile,
									   .LogId			= InOptions.LogId};

	BeginInitializeLogging(LogOptions);

	// Initialize loggers

	auto FileSink = GetFileSink();

	// HTTP server request logging
	std::filesystem::path HttpLogPath = InOptions.DataDir / "logs" / "http.log";
	zen::CreateDirectories(HttpLogPath.parent_path());

	auto HttpSink	= std::make_shared<zen::logging::RotatingFileSink>(HttpLogPath,
																	   /* max size */ 128 * 1024 * 1024,
																	   /* max files */ 16,
																	   /* rotate on open */ true);
	auto HttpLogger = std::make_shared<spdlog::logger>("http_requests", HttpSink);
	spdlog::apply_logger_env_levels(HttpLogger);
	spdlog::register_logger(HttpLogger);

	// Cache request logging
	std::filesystem::path CacheLogPath = InOptions.DataDir / "logs" / "z$.log";
	zen::CreateDirectories(CacheLogPath.parent_path());

	auto CacheSink	 = std::make_shared<zen::logging::RotatingFileSink>(CacheLogPath,
																		/* max size */ 128 * 1024 * 1024,
																		/* max files */ 16,
																		/* rotate on open */ false);
	auto CacheLogger = std::make_shared<spdlog::logger>("z$", CacheSink);
	spdlog::apply_logger_env_levels(CacheLogger);
	spdlog::register_logger(CacheLogger);

	// Jupiter - only log upstream HTTP traffic to file

	auto JupiterLogger = std::make_shared<spdlog::logger>("jupiter", FileSink);
	spdlog::apply_logger_env_levels(JupiterLogger);
	spdlog::register_logger(JupiterLogger);

	// Zen - only log upstream HTTP traffic to file

	auto ZenClientLogger = std::make_shared<spdlog::logger>("zenclient", FileSink);
	spdlog::apply_logger_env_levels(ZenClientLogger);
	spdlog::register_logger(ZenClientLogger);

	FinishInitializeLogging(LogOptions);

	const zen::Oid ServerSessionId = zen::GetSessionId();

	spdlog::apply_all([&](auto Logger) { Logger->info("server session id: {}", ServerSessionId); });
}

void
ShutdownServerLogging()
{
	zen::ShutdownLogging();
}

}  // namespace zen
